﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;

namespace VB
{
    public class FileManager
    {
        public event Action<Exception> OnReadError;
        public event Action OnReadFileMissing;
        public event Action<StreamReader> OnReadReady;

        public event Action<Exception> OnSaveError;
        public string WriteBefore;
        public string WriteAfter;

        private IsolatedStorageFile Storage = IsolatedStorageFile.GetUserStoreForApplication();

        public void Read(string FileName)
        {
            try
            {
                if (Storage.FileExists(FileName))
                {
                    using (var File = Storage.OpenFile(FileName, FileMode.Open, FileAccess.Read))
                    {
                        if (OnReadReady != null)
                            OnReadReady(new StreamReader(File));
                    }
                }
                else
                {
                    if (OnReadFileMissing != null)
                        OnReadFileMissing();
                    else
                        throw new FileNotFoundException();
                }
            }
            catch (Exception ex)
            {
                if (OnReadError != null)
                    OnReadError(ex);
                else
                    MessageBox.Show(ex.Message, "FileManager read error", MessageBoxButton.OK);
            }
        }

        public void Save(string FileName,string Data)
        {
            try
            {
                var FileOpenMode = FileMode.OpenOrCreate;
                if (Storage.FileExists(FileName))
                    FileOpenMode = FileMode.Truncate;

                using (IsolatedStorageFileStream fileStream = Storage.OpenFile(FileName, FileOpenMode, FileAccess.ReadWrite))
                using (StreamWriter writer = new StreamWriter(fileStream))
                {
                    if (WriteBefore != null)
                        writer.Write(WriteBefore);

                    writer.Write(Data);

                    if (WriteAfter != null)
                        writer.Write(WriteAfter);
                }
            }
            catch (Exception ex)
            {
                if (OnSaveError != null)
                    OnSaveError(ex);
                else
                    MessageBox.Show(ex.Message, "FileManager save error", MessageBoxButton.OK);
            }
            
        }
    }
}
